﻿using System;

namespace CSharp进阶_线性表
{
	class Program
	{
		static void Main(string[] args)
		{
			LinkedList<int> list = new LinkedList<int>();
			list.Add(1);
			list.Add(2);
			list.Add(3);
			list.Add(4);
			list.print();
			list.Remove(2);
			list.Remove(3);
			list.print();

			list.Modify(4, 400);
			list.print();
		}
	}
	class LinkedNode<T>
	{
		public T data;
		public LinkedNode<T> prev;
		public LinkedNode<T> next;
		public LinkedNode(T data = default(T))
		{
			this.data = data;
			prev = next = null;
		}
	}
	class LinkedList<T>
	{
		public LinkedNode<T> head;
		public int Count;
		public LinkedList()
		{
			head = new LinkedNode<T>();
			Count = 0;
			head.prev = head;
			head.next = head;
		}
		#region 增-尾插
		public void Add(T data)
		{
			LinkedNode<T> newNode = new LinkedNode<T>(data);
			head.prev.next = newNode;
			newNode.prev = head.prev;
			head.prev = newNode;
			newNode.next = head;
			Count++;
		}
		#endregion
		#region 删
		public void Remove(T data)
		{
			LinkedNode<T> prev = head;
			LinkedNode<T> cur = prev.next;
			while (cur != head && !cur.data.Equals(data))
			{
				prev = cur;
				cur = cur.next;
			}
			if (cur != head)
			{
				prev.next = cur.next;
				cur.next.prev = prev;
				Count--;
			}
		}
		#endregion
		#region 查
		public LinkedNode<T> Contains(T data)
		{
			LinkedNode<T> cur = head.next;
			while (cur != head)
			{
				if (cur.data.Equals(data))
				{
					return cur;
				}
				cur = cur.next;
			}
			return null;
		}
		#endregion
		#region 改
		public void Modify(T data, T newData)
		{
			LinkedNode<T> node = Contains(data);
			if (node != null)
			{
				node.data = newData;
			}
		}
		#endregion
		#region 遍历
		public void print()
		{
			LinkedNode<T> cur = head.next;
			while (cur != head)
			{
				Console.Write(cur.data + "<->");
				cur = cur.next;
			}
			Console.WriteLine();
		}
		#endregion
	}
}
